$(document).ready(function () {
    //Hide the Message "Sorry No media type ... "

    $('#Message').hide();
// Hide The tester Tag if on some other page except for the Home Page
    var Addr = window.location.href;
    if (Addr == 'http://www.themediaant.com/p/advertisers.html' || Addr == 'http://www.themediaant.com/p/media-owners.html' || Addr == 'http://www.themediaant.com/p/about-us.html' || Addr == 'http://www.themediaant.com/p/contact-us_11.html') {
        if (Addr.indexOf('search') == -1) {
            $('.tester').hide();

        }
    }
    else {

        $('.tester').show();
    }
/*
    //Show Filters Only On the Home Page
    if (Addr == 'http://www.themediaant.com/') {
        $('#filters').show();
    }
    else {
        $('#filters').hide();
    }
    */
    //find division which holds media filter
    var $ui = $('#ui_Media');
    //find division which holds Objective filter
    var $ui2 = $('#ui_Objective');
    //find division which holds Income filter
    var $ui3 = $('#ui_Income');
    //find division which holds Reach filter
    var $ui4 = $('#ui_Reach');
    //find division which holds Audience filter
    var $ui5 = $('#ui_TG');
    //Array to store the Applied Media Type Filters
    var filterOne = new Array();
    //Array to store the Applied Objective Type Filters
    var filterTwo = new Array();
    //Array to store the Applied Income Type Filters
    var filterThree = new Array();
    //Array to store the Applied Reach Filters
    var filterFour = new Array();
    //Array to store the Applied Audience Type Filters
    var filterFive = new Array();
    //Array to store the Final Media Types that is to be displayed after calculating the Intersections
    var finalArray = new Array();
    //Stores Sequence of applied filters
    var Seq = new Array();

    //////////////////////////////////Mouse Down Event... Please Do not Make Changes //////////////////////////////////
    $(document).mousedown(function (event) {
        var target = $(event.target);
        if (!target.parents().andSelf().hasClass('sb_DropDownFilters')) {
            $('.sb_DropDownFilters').hide();
        }
    });
    ////////////////////////////////End of Dont Make changes ////////////////////////////////////////////////////////



    ///////////////////////////////Click Event for the Media filter which displays the dropdown/////////////////////
    $ui.find('#btnMediaType').bind('click', function () {
        $ui.find('#upDownIncome')
          .andSelf().find('#UlMedia').show(150);

    });



    ///////////////////////////////Click Event for the Objective filter which displays the dropdown/////////////////////
    $ui2.find('#btnObjective').bind('click', function () {
        $ui2.find('#upDownSex').andSelf()
          .find('#UlObjective').show(150);
    });




    ///////////////////////////////Click Event for the Income filter which displays the dropdown/////////////////////
    $ui3.find('#btnIncome').bind('click', function () {
        $ui3.find('#upDownTown').andSelf()
          .find('#UlIncome')
          .show(150);

    });

    ///////////////////////////////Click Event for the Reach filter which displays the dropdown/////////////////////
    $ui4.find('#btnReach').bind('click', function () {
        $ui4.find('#upDownAge').andSelf()
          .find('#UlReach')
          .show(150);
    });

    ///////////////////////////////Click Event for the Audience(Target Group) filter which displays the dropdown/////////////////////
    $ui5.find('#btnTG').bind('click', function () {
        $ui5.find('#upDownTG').andSelf()
          .find('#UlTG')
          .show(150);
    });

    ////////////////////////////////Map the filterName to the JSON array Name///////////////////////////////////////////////////////
    function mapArray(filterType) {

        if (filterType == "chkOOHScreens")
            return chkOOHScreens;
        else if (filterType == "chkBillsTickets")
            return chkBillsTickets;
        else if (filterType == "chkInnovative")
            return chkInnovative;
        else if (filterType == "chkAmbient")
            return chkAmbient;
        else if (filterType == "chkOnline")
            return chkOnline;
        else if (filterType == "chkTransit")
            return chkTransit;
        else if (filterType == "chkSampling")
            return chkSampling;
        else if (filterType == "chkTraditionalMedia")
            return chkTraditionalMedia;
        else if (filterType == "chkMobile")
            return chkMobile;
        else if (filterType == "chkDatabaseMktg")
            return chkDatabaseMktg;
        else if (filterType == "chkSales")
            return chkSales;
        else if (filterType == "chkInduceTrials")
            return chkInduceTrials;
        else if (filterType == "chkBranding")
            return chkBranding;
        else if (filterType == "chkPhysicalSampling")
            return chkPhysicalSampling;
        else if (filterType == "chkLowerClass")
            return chkLowerClass;
        else if (filterType == "chkUpperMiddleClass")
            return chkUpperMiddleClass;
        else if (filterType == "chkMiddleClass")
            return chkMiddleClass;
        else if (filterType == "chkRich")
            return chkRich;
        else if (filterType == "chkUpperClass")
            return chkUpperClass;
        else if (filterType == "chkLowReach")
            return chkLowReach;
        else if (filterType == "chkMediumReach")
            return chkMediumReach;
        else if (filterType == "chkHighReach")
            return chkHighReach;
        else if (filterType == "chkMixedGroup")
            return chkMixedGroup;
        else if (filterType == "chkKids")
            return chkKids;
        else if (filterType == "chkYouth")
            return chkYouth;
        else if (filterType == "chkAdults")
            return chkAdults;
        else if (filterType == "chkHouseWives")
            return chkHouseWives;
        else if (filterType == "chkStudents")
            return chkStudents;



    }

    /////////////////////////////////////////Gets the Array with Distinct Media Types... (No Repeating of media types) //////////////////////////////////
    function GetUniqueArray(toFindArray) {
        var o = {}, i, l = toFindArray.length, r = [];
        for (i = 0; i < l; i += 1) o[toFindArray[i]] = toFindArray[i];
        for (i in o) r.push(o[i]);
        return r;
    }

    //////////////////////////////////////Creates the small box when any filter is selected /////////////////////////////////////////////////////////////
    function createLabel(title) {
        var div = document.createElement("div");
        div.setAttribute("id", title);
        var span = document.createElement("span");
        span.setAttribute("class", "crossimage");
        var label = document.createElement("input");
        //Assign different attributes to the element.
        label.setAttribute("type", "button");
        label.setAttribute("class", "smallBox");
        label.setAttribute("id", title);
        label.setAttribute("value", title);
        div.appendChild(label);
        div.appendChild(span);
        var foo = document.getElementById("selected_filter");
        foo.appendChild(div);
    }


    ////////////////////////////////////////// Hides all the media Types from the Page ///////////////////////////////////////////////////////////////////////
    function hideAllMedia() {
        for (var i = 0; i < All.length; i++) {
            var Media = '#' + All[i].ID;
            $(Media).hide();
        }
    }

    /////////////////////////////////////////Shows all the media Types on the page/ //////////////////////////////////////////////////////////////////////////
    function showAllMedia() {
        for (var i = 0; i < All.length; i++) {
            var Media = '#' + All[i].ID;
            $(Media).show();
        }
    }


    //////////////////////////////////// Handles the click  event on the small Box //////////////////////////////////////////////////////////////////////////
    $('.smallBox').live('click', function () {

        removeCheck($(this).val());
        removeLabel($(this));
        RemoveMediaFilter();
        RemoveIncomeFilter();
        RemoveObjectiveFilter();
        RemoveReachFilter();
        RemoveTGFilter();
    });

    ////////////////////////////////////////////Removes the Small Box from the Page //////////////////////////////////////////////////////////////////
    function removeLabel(title) {
        $(title).remove();
    }

    ///////////////////////////////////////////Removes the Box from the Page ///////////////////////////////////////////////////////////////////////
    function removeLabelByTitle(title) {

        var parent = document.getElementById('selected_filter');
        var toRemove = document.getElementById(title);
        parent.removeChild(toRemove);
    }

    /////////////////////////////////////////Remove The check from the CheckBox when Small box is removes ///////////////////////////////////////
    function removeCheck(title) {

        var chkbox = "#chk" + title;
        chkbox = chkbox.replace(' ', '');
        chkbox = chkbox.replace(' ', '');
        chkbox = chkbox.replace('/', '');

        if ($(chkbox).is(':checked')) {
            $(chkbox).attr('checked', false);
        }
    }

    ////////////////////////////////////////// Function which calculates the final Array of media types that is to be displayed ///////////////////////////////////////////////
    function findIntersection() {

        var tempoArray = new Array();
        if (Seq.length == 0) {

        }
        else if (Seq.length == 1) {
            tempoArray = returnArrayName(Seq[0]);
        }
        else {
            tempoArray = returnArrayName(Seq[0]);
            for (var i = 1; i < Seq.length; i++) {
                tempoArray = InterSection(tempoArray, returnArrayName(Seq[i]));
            }
        }

        hideAllMedia();

        if ($(":checkbox:checked").length == 0) {
            $('#Message').hide();
            showAllMedia();

        } else {
            if (tempoArray.length == 0) {
                $('#Message').show();
            }
            else {
                $('#Message').hide();
                for (var i = 0; i < tempoArray.length; i++) {
                    var media = "#" + tempoArray[i];
                    $(media).show();
                }
            }
        }

    }

    ///////////////////////////////////////////////////////////////////////Find Intersection of two array ////////////////////////////////////////////////////////
    function InterSection(array1, array2) {
        var temp = new Array();
        for (var k = 0; k < array2.length; k++) {
            if (array1.indexOf(array2[k]) != -1) {
                temp.push(array2[k]);
            }
        }
        return temp;
    }

    ////////////////////////////////////////////////////////////Map The Array Name ////////////////////////////////////////////////////////////
    function returnArrayName(ArrayName) {

        if (ArrayName == "filterOne")
            return filterOne;
        else if (ArrayName == "filterTwo")
            return filterTwo;
        else if (ArrayName == "filterThree")
            return filterThree;
        else if (ArrayName == "filterFour")
            return filterFour;
        else if (ArrayName == "filterFive")
            return filterFive;


    }


    ////////////////////////////////////////////////////Media Filter///////////////////////////////////////////////////////////////////////
    //////////////APPLY THE MEDIA FILTER .. QUERY THE JSON FILE AND GET THE MEDIA FILTER ASSOCIATED WITH THE RESPECTIVE CHECKBOX CLICKED//////
    function ApplyMediaFilter(filterType) {

        var tempArr = new Array();
        tempArr = mapArray(filterType);

        for (var i = 0; i < tempArr.length; i++) {
            filterOne.push(tempArr[i].ID);
        }
        var finalArray = new Array();
        filterOne = GetUniqueArray(filterOne);

    }


    //////////////////////// Function which takes care of when a checkbox is unchecked//////////////////////////////////////////////////
    function RemoveMediaFilter() {
        while (filterOne.length != 0) {
            filterOne.pop();
        }
        $(".chkboxMedia:checked").each(function () {
            ApplyMediaFilter($(this).attr('id'));
        }); checkSeqMedia();
        findIntersection();


    }



    ////////////////////////////////////CheckBox Check event function /////////////////////////////////////////////////////////////
    $('.chkboxMedia').bind('click', function () {

        if ($(this).is(':checked')) {
            createLabel($(this).val());
            ApplyMediaFilter($(this).attr('id'));
        }
        else {
            removeLabelByTitle($(this).val());
            RemoveMediaFilter();
        }
        checkSeqMedia();
        findIntersection();

    });

    ////////////////////////////////////filter Label Click Event //////////////////////////////////////////////////////////////////////
    $('.lblMedia').bind('click', function () {

        if ($(this).prev().is(':checked')) {
            $(this).prev().attr('checked', false);
            removeLabelByTitle($(this)
            .prev().val());
            RemoveMediaFilter();
        }
        else {
            $(this).prev().attr('checked', true);
            ApplyMediaFilter($(this).prev().attr('id'));
            createLabel($(this).prev().val());
        }
        checkSeqMedia();
        findIntersection();
    });


    /////////////////////////////////////////Adds/Removes the Media Filter Name from the Sequence/////////////////////////////////////////////////////
    function checkSeqMedia() {
        if ($(".chkboxMedia:checked").length != 0) {
            if (Seq.indexOf('filterOne') == -1) {
                Seq.push('filterOne');
            }
        }
        else {
            if (Seq.indexOf('filterOne') != -1) {
                var index = Seq.indexOf('filterOne');
                Seq.splice(index, 1);
            }
        }


    }



    //////////////////////////////////////////////////////End Media Filter ///////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////Objective Filters //////////////////////////////////////////////////////////////


    //////////////APPLY THE Objective FILTER .. QUERY THE JSON FILE AND GET THE Objective FILTER ASSOCIATED WITH THE RESPECTIVE CHECKBOX CLICKED//////    
    function ApplyObjectiveFilter(filterType) {

        var tempArr = new Array();
        tempArr = mapArray(filterType);

        for (var i = 0; i < tempArr.length; i++) {
            filterTwo.push(tempArr[i].ID);
        }
        var finalArray = new Array();
        filterTwo = GetUniqueArray(filterTwo);

    }

    //////////////////////// Function which takes care of when a checkbox is unchecked//////////////////////////////////////////////////
    function RemoveObjectiveFilter() {

        while (filterTwo.length != 0) {
            filterTwo.pop();
        }
        $(".chkboxObjective:checked").each(function () {
            ApplyObjectiveFilter($(this).attr('id'));
        }); checkSeqObjective();

        findIntersection();

    }

    ////////////////////////////////////CheckBox Check event function /////////////////////////////////////////////////////////////
    $('.chkboxObjective').bind('click', function () {

        if ($(this).is(':checked')) {
            createLabel($(this).val());
            ApplyObjectiveFilter($(this).attr('id'));
        }
        else {
            removeLabelByTitle($(this).val());
            RemoveObjectiveFilter();
        }
        checkSeqObjective();
        findIntersection();
    });

    /////////////////////////////////Objective Filter label Click event//////////////////////////////////////////////////////////////////
    $('.lblObjective').bind('click', function () {

        if ($(this).prev().is(':checked')) {
            $(this).prev().attr('checked', false);
            removeLabelByTitle($(this).prev().val());
            RemoveObjectiveFilter();
        }
        else {
            $(this).prev().attr('checked', true);
            ApplyObjectiveFilter($(this).prev().attr('id'));
            createLabel($(this).prev().val());
        }
        checkSeqObjective();
        findIntersection();

    });



    /////////////////////////////////////////Adds/Removes the Media Filter Name from the Sequence/////////////////////////////////////////////////////
    function checkSeqObjective() {
        if ($(".chkboxObjective:checked").length != 0) {
            if (Seq.indexOf('filterTwo') == -1) {
                Seq.push('filterTwo');
            }
        }
        else {
            if (Seq.indexOf('filterTwo') != -1) {
                var index = Seq.indexOf('filterTwo');
                Seq.splice(index, 1);
            }
        }


    }





    //////////////////////////////////////////////////////////////End Objective Filter//////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////Start Income Filter///////////////////////////////////////////


    ////////////////////////////////////Apply Income Filter/////////////////////////////////////////////////
    function ApplyIncomeFilter(filterType) {

        var tempArr = new Array();
        tempArr = mapArray(filterType);

        for (var i = 0; i < tempArr.length; i++) {
            filterThree.push(tempArr[i].ID);
        }
        var finalArray = new Array();
        filterThree = GetUniqueArray(filterThree);

    }


    /////////////////////////////////Remove A Income Filter//////////////////////////////////////////////
    function RemoveIncomeFilter() {

        while (filterThree.length != 0) {
            filterThree.pop();
        }
        $(".chkboxIncome:checked").each(function () {
            ApplyIncomeFilter($(this).attr('id'));
        }); checkSeqIncome();
        findIntersection();

    }
    //////////////////////////////Check box check event///////////////////////////
    $('.chkboxIncome').bind('click', function () {

        if ($(this).is(':checked')) {
            createLabel($(this).val());
            ApplyIncomeFilter($(this).attr('id'));
        }
        else {
            removeLabelByTitle($(this).val());
            RemoveIncomeFilter();
        }
        checkSeqIncome()
        findIntersection();
    });

    //////////////////////////////////////Income filter Label Click Event///////////////////////////////////////
    $('.lblIncome').bind('click', function () {

        if ($(this).prev().is(':checked')) {
            $(this).prev().attr('checked', false);
            removeLabelByTitle($(this).prev().val());
            RemoveIncomeFilter();
        }
        else {
            $(this).prev().attr('checked', true);
            ApplyIncomeFilter($(this).prev().attr('id'));
            createLabel($(this).prev().val());
        }
        checkSeqIncome()
        findIntersection();
    });

    
    ///////////////////////////////////////////////Adds/remove in the sequence Array ///////////////////////////////////////
    function checkSeqIncome() {
        if ($(".chkboxIncome:checked").length != 0) {
            if (Seq.indexOf('filterThree') == -1) {
                Seq.push('filterThree');
            }
        }
        else {
            if (Seq.indexOf('filterThree') != -1) {
                var index = Seq.indexOf('filterThree');
                Seq.splice(index, 1);
            }
        }


    }

    /////////////////////////////////////////End Income Filter////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////Start Reach Filter//////////////////////////////////////////



    //////////////////////////////////////////////////////////////////////Apply Reach Filter//////////////////////////////////////
    function ApplyReachFilter(filterType) {

        var tempArr = new Array();
        tempArr = mapArray(filterType);

        for (var i = 0; i < tempArr.length; i++) {
            filterFour.push(tempArr[i].ID);
        }
        var finalArray = new Array();
        filterFour = GetUniqueArray(filterFour);

    }


    /////////////////////////////Remove A Reach Filter///////////////////////////////////////////////////////////////////////
    function RemoveReachFilter() {

        while (filterFour.length != 0) {
            filterFour.pop();
        }
        $(".chkboxReach:checked").each(function () {
            ApplyReachFilter($(this).attr('id'));
        }); checkSeqReach();
        findIntersection();

    }

    //////////////////////////////Checkbox check in reach Filter/////////////////////////////////////////////////////
    $('.chkboxReach').bind('click', function () {
        if ($(this).is(':checked')) {
            createLabel($(this).val());
            ApplyReachFilter($(this).attr('id'));
        }
        else {
            removeLabelByTitle($(this).val());
            RemoveReachFilter();
        }
        checkSeqReach()
        findIntersection();
    });

    ////////////////////////////////////////Label Click On reach filter /////////////////////////////////////////////////
    $('.lblReach').bind('click', function () {

        if ($(this).prev().is(':checked')) {
            $(this).prev().attr('checked', false);
            removeLabelByTitle($(this).prev().val());
            RemoveReachFilter();
        }
        else {
            $(this).prev().attr('checked', true);
            ApplyReachFilter($(this).prev().attr('id'));
            createLabel($(this).prev().val());
        }
        checkSeqReach()
        findIntersection();
    });

    
    /////////////////////////////////Adds/ Removes the Reach filter from sequence//////////////////////////////////
    function checkSeqReach() {
        if ($(".chkboxReach:checked").length != 0) {
            if (Seq.indexOf('filterFour') == -1) {
                Seq.push('filterFour');
            }
        }
        else {
            if (Seq.indexOf('filterFour') != -1) {
                var index = Seq.indexOf('filterFour');
                Seq.splice(index, 1);
            }
        }


    }

    ////////////////////////////////////////////////////End Reach Filter //////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////Start TG Filter///////////////////////////////////////////////////////

    ///////////////////////////////////////////Apply Audience  Filter/////////////////////////////////////
    function ApplyTGFilter(filterType) {

        var tempArr = new Array();
        tempArr = mapArray(filterType);

        for (var i = 0; i < tempArr.length; i++) {
            filterFive.push(tempArr[i].ID);
        }
        var finalArray = new Array();
        filterFive = GetUniqueArray(filterFive);

    }


    ///////////////////////////Remove A Audience Filter/////////////////////////////////////////////////////////////////////////
    function RemoveTGFilter() {

        while (filterFive.length != 0) {
            filterFive.pop();
        }
        $(".chkboxTG:checked").each(function () {
            ApplyTGFilter($(this).attr('id'));
        }); checkSeqTG();
        findIntersection();

    }



    ////////////////////////////Checkbox click on audience Filter ////////////////////////////////////////////////////////
    $('.chkboxTG').bind('click', function () {

        if ($(this).is(':checked')) {
            createLabel($(this).val());
            ApplyTGFilter($(this).attr('id'));
        }
        else {
            removeLabelByTitle($(this).val());
            RemoveTGFilter();
        }
        checkSeqTG()
        findIntersection();
    });

    /////////////////////////////////// Label Click of audience filter
    $('.lblTG').bind('click', function () {

        if ($(this).prev().is(':checked')) {
            $(this).prev().attr('checked', false);
            removeLabelByTitle($(this).prev().val());
            RemoveTGFilter();
        }
        else {
            $(this).prev().attr('checked', true);
            ApplyTGFilter($(this).prev().attr('id'));
            createLabel($(this).prev().val());
        }
        checkSeqTG()
        findIntersection();
    });

    
    //////////////////////////////////Adds/Remove Audience Filter to the sequence/////////////////////
    function checkSeqTG() {
        if ($(".chkboxTG:checked").length != 0) {
            if (Seq.indexOf('filterFive') == -1) {
                Seq.push('filterFive');
            }
        }
        else {
            if (Seq.indexOf('filterFive') != -1) {
                var index = Seq.indexOf('filterFive');
                Seq.splice(index, 1);
            }
        }


    }

});































